from fastapi import APIRouter, File, Form, Response
from common import PDFWriter
from models import OpenaiModel
import pdfplumber
import io


router = APIRouter()


@router.post(path='/trans/pdf')
def transPdf():
    pdf = pdfplumber.open('test1.pdf')
    text = pdf.pages[0].extract_text()
    return text


@router.post(path='/upload/trans/pdf')
def uploadTransPdf(pdf: bytes = File(),
                   fromLanguage: str = Form(),
                   toLanguage: str = Form()):
    contents = io.BytesIO(pdf)
    file = pdfplumber.open(contents)
    text = file.pages[0].extract_text_lines(layout=True)

    trans_message = []
    for t in text:
        trans_message.append(t['text'])
    msg = "\n".join(trans_message)
    openai_model = OpenaiModel()
    response_message = openai_model.request_openai(msg, fromLanguage, toLanguage)
    # <br/>
    # response_message = """1. Support for Graphical User Interface (GUI) to enhance usability.
    # 2. Add support for preserving the original layout of the source PDF.
    # 3. Service-oriented: Provide translation services support in the form of an API.
    # 4. Add support for other languages."""
    print(response_message)
    # print(response_message.split('\n'))
    # print(response_message.replace('\n', '0000'))
    print('from language {} to {}'.format(fromLanguage, toLanguage))
    pdf_writer = PDFWriter()
    p = pdf_writer.pdf_writer(response_message.split('\n'))
    response = Response(content=p, media_type='application/pdf')
    response.headers["Content-Disposition"] = "attachment; filename=translated.pdf"
    return response
